package weaver.interfaces.cyjt.duss.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author dusongsong
 * @date 2024年11月20日 15:15
 */
public class KingdeeUtil extends BaseBean {

    private static final MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
    private static final int CONNECT_TIMEOUT_MILLIS = 60 * 1000; // 60秒
    private static final int READ_TIMEOUT_MILLIS = 60 * 1000; // 60秒
    private static final int WRITE_TIMEOUT_MILLIS = 60 * 1000; // 60秒
    private OkHttpClient client;
    // 定义常量
    private static final String RES_CODE_ZERO = "0";

    public KingdeeUtil() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .readTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .writeTimeout(WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .build();
    }

    /**
     * 处理金蝶财务收款单
     *
     * @param paramsJson
     * @return
     */
    public JSONObject handleKingdeeRecBill(JSONObject paramsJson, String requestid) {
        RecordSet rs = new RecordSet();
        Map<String, Object> apilogMap = new HashMap<>();
        rs.executeQuery("select * from uf_jdbwpzb where jkbm='OASaveRecBill'");
        rs.next();
        String jkmc = Util.null2String(rs.getString("jkmc"));
        String apiUrl = Util.null2String(rs.getString("qqdz"));
        writeLog(">>>>>handleKingdeeBill>>>>>"+jkmc+">>>>>paramsJson", paramsJson);
        JSONObject resultJson = sendOKHttpPostRequest(apiUrl, paramsJson.toJSONString());
        writeLog(">>>>>handleKingdeeBill>>>>>"+jkmc+">>>>>resultJson", resultJson);
        apilogMap.put("jkmc", jkmc);
        apilogMap.put("jkqqcs", paramsJson);
        apilogMap.put("jkxycs", resultJson);
        apilogMap.put("jkqqdz", apiUrl);
        apilogMap.put("jkdysj", DateUtil.getFullDate());
        apilogMap.put("jktgf", "金蝶");
        apilogMap.put("lcqqid", requestid);
        insertModelData(apilogMap);
        return resultJson;
    }

    /**
     * 处理金蝶财务付款单
     *
     * @param paramsJson
     * @return
     */
    public JSONObject handleKingdeePayBill(JSONObject paramsJson, String requestid) {
        RecordSet rs = new RecordSet();
        Map<String, Object> apilogMap = new HashMap<>();
        rs.executeQuery("select * from uf_jdbwpzb where jkbm='OASavePayBill'");
        rs.next();
        String jkmc = Util.null2String(rs.getString("jkmc"));
        String apiUrl = Util.null2String(rs.getString("qqdz"));
        writeLog(">>>>>handleKingdeeBill>>>>>"+jkmc+">>>>>paramsJson"+ paramsJson);
        JSONObject resultJson = sendOKHttpPostRequest(apiUrl, paramsJson.toJSONString());
        writeLog(">>>>>handleKingdeeBill>>>>>"+jkmc+">>>>>resultJson"+ resultJson);
        apilogMap.put("jkmc", jkmc);
        apilogMap.put("jkqqcs", paramsJson);
        apilogMap.put("jkxycs", resultJson);
        apilogMap.put("jkqqdz", apiUrl);
        apilogMap.put("jkdysj", DateUtil.getFullDate());
        apilogMap.put("jktgf", "金蝶");
        apilogMap.put("lcqqid", requestid);
        insertModelData(apilogMap);
        return resultJson;
    }

    /**
     * 处理金蝶财务应付单
     *
     * @param paramsJson
     * @return
     */
    public JSONObject handleKingdeeApfinapBill(JSONObject paramsJson, String requestid) {
        RecordSet rs = new RecordSet();
        Map<String, Object> apilogMap = new HashMap<>();
        rs.executeQuery("select * from uf_jdbwpzb where jkbm='OASaveApfinapBill'");
        rs.next();
        String jkmc = Util.null2String(rs.getString("jkmc"));
        String apiUrl = Util.null2String(rs.getString("qqdz"));
        writeLog(">>>>>handleKingdeeBill>>>>>"+jkmc+">>>>>paramsJson"+ paramsJson);
        JSONObject resultJson = sendOKHttpPostRequest(apiUrl, paramsJson.toJSONString());
        writeLog(">>>>>handleKingdeeBill>>>>>"+jkmc+">>>>>resultJson"+ resultJson);
        apilogMap.put("jkmc", jkmc);
        apilogMap.put("jkqqcs", paramsJson);
        apilogMap.put("jkxycs", resultJson);
        apilogMap.put("jkqqdz", apiUrl);
        apilogMap.put("jkdysj", DateUtil.getFullDate());
        apilogMap.put("jktgf", "金蝶");
        apilogMap.put("lcqqid", requestid);
        insertModelData(apilogMap);
        return resultJson;
    }
    /**
     * 处理金蝶财务应收单
     *
     * @param paramsJson
     * @return
     */
    public JSONObject handleKingdeeArfinarBill(JSONObject paramsJson, String requestid) {
        RecordSet rs = new RecordSet();
        Map<String, Object> apilogMap = new HashMap<>();
        rs.executeQuery("select * from uf_jdbwpzb where jkbm='OASaveArfinarBill'");
        rs.next();
        String jkmc = Util.null2String(rs.getString("jkmc"));
        String apiUrl = Util.null2String(rs.getString("qqdz"));
        writeLog(">>>>>handleKingdeeBill>>>>>"+jkmc+">>>>>paramsJson"+ paramsJson);
        JSONObject resultJson = sendOKHttpPostRequest(apiUrl, paramsJson.toJSONString());
        writeLog(">>>>>handleKingdeeBill>>>>>"+jkmc+">>>>>resultJson"+ resultJson);
        apilogMap.put("jkmc", jkmc);
        apilogMap.put("jkqqcs", paramsJson);
        apilogMap.put("jkxycs", resultJson);
        apilogMap.put("jkqqdz", apiUrl);
        apilogMap.put("jkdysj", DateUtil.getFullDate());
        apilogMap.put("jktgf", "金蝶");
        apilogMap.put("lcqqid", requestid);
        insertModelData(apilogMap);
        return resultJson;
    }



    /**
     * 获取token
     *
     * @return
     */
    private String getToken() {
        String token = "";
        JSONObject returnJson = getTokenBaseInfo();
        String apiUrl = returnJson.getString("apiUrl");
        JSONObject paramJson = returnJson.getJSONObject("paramJson");
        paramJson.put("nonce", UUID.randomUUID().toString());
        paramJson.put("timestamp", DateUtil.getFullDate());
        try {
            RequestBody body = RequestBody.create(mediaType, paramJson.toJSONString());
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            writeLog(">>>>>getToken>>>>>result", result);
            response.body().close(); // 保证资源被释放
            // 增加对HTTP状态码的检查
            if (response.isSuccessful()) {
                if (!result.isEmpty()) {
                    JSONObject resultJsonObj = JSONObject.parseObject(result);
                    String errorCode = resultJsonObj.getString("errorCode");
                    if (RES_CODE_ZERO.equals(errorCode)) {
                        token = resultJsonObj.getJSONObject("data").getString("access_token");
                    }
                }
            }
        } catch (Exception e) {
            writeLog(">>>>>sendOKHttpPostRequest>>>>>Exception e:", e);
        }
        return token;
    }

    /**
     * Post请求
     *
     * @param params
     * @param apiUrl
     * @return
     */
    public JSONObject sendOKHttpPostRequest(String apiUrl, String params) {
        String accesstoken = getToken();
        JSONObject resultJson = new JSONObject();
        String responseMsg = "";
        try {
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("POST", body)
                    .addHeader("accesstoken", accesstoken)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            response.body().close(); // 保证资源被释放
            // 增加对HTTP状态码的检查
            if (!response.isSuccessful()) {
                responseMsg = "response code :" + response.code();
            } else {
                if (!result.isEmpty()) {
                    resultJson.put("datas", result);
                    responseMsg = "success";
                } else {
                    responseMsg = "response result is null";
                }
            }
        } catch (Exception e) {
            responseMsg = "response timeout or network error";
            writeLog(">>>>>sendOKHttpPostRequest>>>>>Exception e:", e);
        }
        resultJson.put("message", responseMsg);
        return resultJson;
    }

    private JSONObject getTokenBaseInfo() {
        RecordSet rs = new RecordSet();
        JSONObject returnJson = new JSONObject();
        JSONObject paramJson = new JSONObject();
        rs.executeQuery("select * from uf_jdbwpzb where jkbm='getToken'");
        rs.next();
        String mainid = Util.null2String(rs.getString("id"));
        String apiUrl = Util.null2String(rs.getString("qqdz"));
        rs.executeQuery("select * from uf_jdbwpzb_dt1 where mainid=?", mainid);
        while (rs.next()) {
            String qqcsj = Util.null2String(rs.getString("qqcsj"));
            String qqcsz = Util.null2String(rs.getString("qqcsz"));
            paramJson.put(qqcsj, qqcsz);
        }
        returnJson.put("apiUrl", apiUrl);
        returnJson.put("paramJson", paramJson);
        return returnJson;
    }

    /**
     * 建模权限重构
     *
     * @param userid
     * @param formmodeid
     * @param id
     */
    private void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    /**
     * 将数据插入表单建模
     *
     * @param map
     */
    private void insertModelData(Map<String, Object> map) {
        String tablename = "uf_apilog";
        int userid = 1;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        //查询该模块表名
        try {
            rs.executeQuery("select a.id from modeinfo a left join workflow_bill b on a.formid=b.id where b.tablename='" + tablename + "'");
            rs.next();
            int modeid = Util.getIntValue(rs.getString("id"));
            String uuid = UUID.randomUUID().toString();
            String insSql = "insert into " + tablename
                    + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values" +
                    "('" + uuid + "','" + userid + "','" + TimeUtil.getCurrentDateString() + "','" + TimeUtil.getOnlyCurrentTimeString() + "','" + modeid + "')";
            rs.executeUpdate(insSql);
            rs1.executeQuery("select id from " + tablename + " where modeuuid='" + uuid + "'");
            rs1.next();
            int dataid = Util.getIntValue(rs1.getString("id"));
            if (dataid > 0) {
                //遍历数据 进行update
                String updatesql = "update " + tablename + " set ";
                Set<String> keySet = map.keySet();
                for (String key : keySet) {
                    if ("jkqqcs".equals(key) && Util.null2String(map.get(key)).length() >= 4000) {
                        updatesql += key + "='" + map.get(key).toString().substring(0, 4000) + "',";
                    } else {
                        updatesql += key + "='" + map.get(key).toString() + "',";
                    }
                }
                if (updatesql.endsWith(",")) {
                    updatesql = updatesql.substring(0, updatesql.length() - 1);
                    updatesql += " where id=" + dataid;
                    if (!rs.executeUpdate(updatesql)) {
                        rs1.executeUpdate("delete from " + tablename + " where id=?", dataid);
                    }
                }
                //进行权限重构
                newModeRight(userid, modeid, dataid);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
